package com.neteast.bustruck.http

import android.text.TextUtils
import android.util.Log
import com.neteast.bustruck.BuildConfig
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import okhttp3.Response
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory


object RetrofitClient {



    var token:String =""
    val instance: Retrofit by lazy {
        val loggingInterceptor = HttpLoggingInterceptor()
        loggingInterceptor.level = HttpLoggingInterceptor.Level.BODY
        if(BuildConfig.DEBUG){
            val client = OkHttpClient.Builder()
                .addInterceptor(loggingInterceptor)
                .addInterceptor(object :Interceptor{
                    override fun intercept(chain: Interceptor.Chain): Response {
                        if(TextUtils.isEmpty(token)){
                            val request = chain.request()
                            return chain.proceed(request)
                        }else{
                            val originalRequest = chain.request()
                            val requestWithHeader = originalRequest.newBuilder()
                                .header("Authorization", "Bearer $token")
                                .build()
                            return chain.proceed(requestWithHeader)
                        }
                    }

                })
                .build()

            Retrofit.Builder()
                .baseUrl(BuildConfig.BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .client(client)
                .build()
        }else{
            val client = OkHttpClient.Builder()
                .addInterceptor(object :Interceptor{
                    override fun intercept(chain: Interceptor.Chain): Response {
                        if(TextUtils.isEmpty(token)){
                            val request = chain.request()
                            return chain.proceed(request)
                        }else{
                            val originalRequest = chain.request()
                            val requestWithHeader = originalRequest.newBuilder()
                                .header("Authorization", "Bearer $token")
                                .build()
                            return chain.proceed(requestWithHeader)
                        }
                    }

                })
                .build()

            Retrofit.Builder()
                .baseUrl(BuildConfig.BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .client(client)
                .build()
        }

    }
}